//
//  NSURLProtocolCustom.m
//  KissHealth
//
//  Created by Mark on 2017/1/19.
//  Copyright © 2017年 Mark. All rights reserved.
//

#import "NSURLProtocolCustom.h"
#import "KHCustomTool.h"
#import "KHImageTool.h"

@implementation NSURLProtocolCustom
//重写方法 1
+(BOOL)canInitWithRequest:(NSURLRequest *)request{
    NSLog(@"canInitWithRequest");
    NSLog(@"-----%@",request.URL.absoluteString);
    // 这里是html 渲染时候入口，来处理自定义标签 如 "myapp",若return YES 则会执行接下来的 -startLoading方法
    if ([request.URL.scheme caseInsensitiveCompare:@"local"] == NSOrderedSame)
         {
        return YES;
    }
    return NO;
    
}

//重写方法
+(NSURLRequest*)canonicalRequestForRequest:(NSURLRequest *)request{
    return request;
}

//重写方法
-(void)startLoading{
    
    //处理自定义标签 ，并实现内嵌本地资源
    NSLog(@"startLoading");
    
    NSLog(@"%@", super.request.URL);
    
    NSString *url=super.request.URL.absoluteString;// 得到//image1.png"
    
    NSString *base64String = [KHCustomTool getValue:url];
    UIImage *image = [KHImageTool imageWithBase64String:base64String];
    if (!image) {
        //若资源找不到则需要调用
        //错误处理，而不是直接返回nil  不进行任何处理，这样会导致js 无法正常加载、运行
//        [self sendResponseWithResponseCode:401 data:nil mimeType:nil];//重要
        return;
    }
//    [self sendResponseWithResponseCode:200 data:data mimeType:mimeType];
    NSData *data = [KHImageTool dataWithImage:image];
    NSString *mimeType = [KHImageTool mimeTypeWithImage1:image];
    // 这里需要用到MIMEType
    NSURLResponse *response = [[NSURLResponse alloc] initWithURL:super.request.URL
                               
                                                        MIMEType:mimeType
                               
                                           expectedContentLength:-1
                               
                                                textEncodingName:nil];
    
    //硬编码 开始嵌入本地资源到web中
    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    [[self client] URLProtocol:self didLoadData:data];
    [[self client] URLProtocolDidFinishLoading:self];
    
}

-(void)stopLoading{
}

@end
